const db = require('../db')

// 获取列表
exports.list = (req, res) => {
  const { pageIndex, pageSize, searchKey } = req.query;

  // 查询总数
  db.query(`select count(*) as total from user where name like '%${searchKey}%'`, (err, data1) => {
    if(err) {
      return res.send('错误：' + err.message);
    }
    const total = data1[0].total;

    // 查询范围内的数据
    const offset = (pageIndex - 1) * pageSize;
    const sql = `select * from user where name like '%${searchKey}%' limit ${pageSize} offset ${offset}`
    db.query(sql, (err, data2) => {
      if(err) {
        return res.send('错误：' + err.message);
      }
      res.send({
        code: 200,
        message: 'success',
        data: {
          list: data2,
          total: Number(total),
          current: Number(pageIndex)
        }
      })
    })
  })
}

// 删除用户
exports.delete = (req, res) => {
  const { id } = req.query;
  const sql = `delete from user where id=${id}`;
  db.query(sql, (err, data) => {
    if(err) {
      return res.send({ code: 400, message: '删除失败', data: null });
    }
    res.send({ code: 200, message: '删除成功', data: null });
  });
}

// 添加用户
exports.add = (req, res) => {
  const { name, username, userpwd, sex, age } = req.query;
  const sql = `insert into user (name, username, userpwd, sex, age) values ('${name}','${username}','${userpwd}','${sex}',${age})`;
  db.query(sql, (err, data) => {
    if(err) {
      const code = err.code;
      let msg = '';
      switch(code) {
        case 'ER_DUP_ENTRY': msg = '登录名已存在'; break;
        default: msg = err.message; break;
      }
      return res.send({ code: 400, message: '添加失败，' + msg, data: null });
    }
    res.send({ code: 200, message: '添加成功', data: null })
  });
}

// 修改用户信息
exports.update = (req, res) => {
  const { id, name, username, userpwd, sex, age } = req.query;
  const sql = `update user set name='${name}', username='${username}', userpwd='${userpwd}', sex='${sex}', age=${age} where id=${id}`;
  db.query(sql, (err, data) => {
    if(err) {
      return res.send({ code: 400, message: '更新失败', data: null })
    }
    res.send({ code: 200, message: '更新成功', data: null })
  })
}